<template>
  <div class="app-container">
    <el-dialog :title="titles[flag]" :visible.sync="dialogVisible" width="60%" append-to-body>
      <el-form ref="form" :model="form" :disabled="flag==1" v-loading="loading">
        <el-row :gutter="10">
         <el-col :span="12">
           <el-form-item label="订单编号" prop="orderNo" required>
             <div v-if="flag==1">{{form.orderNo}}</div>
             <el-input v-else v-model="form.orderNo" placeholder="自动生成" disabled/>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="下单日期" prop="orderDate">
             <div v-if="flag==1">{{form.orderDate}}</div>
             <el-input v-else v-model="form.orderDate"  placeholder="自动生成" disabled/>
           </el-form-item>
         </el-col>
        </el-row>
        <el-row :gutter="10">
         <el-col :span="12">
           <el-form-item label="供应商" prop="supplierId" required>
             <div v-if="flag==1">{{form.supplierName}}</div>
             <el-select v-else v-model="form.supplierId"  style="width: 100%">
               <el-option
                 v-for="item in unitList"
                 :key="item.id"
                 :label="item.merchantName"
                 :value="item.id">
               </el-option>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="折扣金额(元)" prop="discountAmount">
             <div v-if="flag==1">{{form.discountAmount}}</div>
             <el-input v-else type="number" v-model="form.discountAmount" min="0" placeholder="请输入"/>
           </el-form-item>
         </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="付款日期" prop="paidDay">
              <div v-if="flag==1">{{form.paidDay}}</div>
              <el-date-picker v-else v-model="form.paidDay" type="date" placeholder="请输入"  style="width: 100%"
                              value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <div v-if="flag==1">{{form.deliveryDate}}</div>
              <el-date-picker v-else v-model="form.deliveryDate" type="date" placeholder="请输入"  style="width: 100%"
                              value-format="yyyy-MM-dd" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="采购部门" prop="deptId">
              <div v-if="flag==1">{{form.deptName}}</div>
              <treeselect v-else  class="myInput" :default-expand-level="1" v-model="form.deptId" :options="deptList"
                          placeholder="请选择" noResultsText="无数据"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="handleId">
              <div v-if="flag==1">{{form.handlerName}}</div>
              <el-select v-else v-model="form.handleId"  style="width: 100%">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName+'（'+item.deptName+'）'"
                  :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="myTitle">采购项目</div>
      <div v-if="flag==0">
        <el-button type="primary" plain @click="list.push({})">新增</el-button>
        <el-button  plain @click="list=[]">清空</el-button>
      </div>
      <el-table
        :data="list"
        max-height="500"
       >
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="productType" label="商品类型" align="center">
          <template slot-scope="scope">
            <div v-if="flag==1">
              <dict-tag :options="dict.type.product_type" :value="scope.row.productType"/>
            </div>
            <el-select v-else v-model="scope.row.productType" filterable style="width: 100%"
            @change="changeType(scope.row)" placeholder="请选择(必填)">
              <el-option
                v-for="item in dict.type.product_type"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" align="center">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.productName}}</div>
            <el-select v-else v-model="scope.row.productId" filterable style="width: 100%"
            @change="changeGood(scope.row)" placeholder="请选择(必填)">
              <el-option
                v-for="item in scope.row.goodList"
                :key="item.id"
                :label="item.productName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="imageUrl" label="图片" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="!scope.row.imageUrl">暂无</div>
            <el-image
              v-else
              style="width: 80px;height: 80px"
              :src="scope.row.imageUrl"
              fit="contain"
              :preview-src-list="[scope.row.imageUrl]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" align="center" width="80"/>
        <el-table-column prop="quantity" label="数量" align="center" width="80">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.quantity}}</div>
            <el-input v-else type="number" v-model="scope.row.quantity" :min='0' placeholder="请输入(必填)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价(元)" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.unitPrice}}</div>
            <el-input v-else type="number" v-model="scope.row.unitPrice" :min='0' placeholder="请输入(必填)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率(%)" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.taxRate}}</div>
            <el-input v-else type="number" v-model="scope.row.taxRate" :min='0' placeholder="请输入(必填)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="taxPrice" label="含税单价(元)" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.taxPrice}}</div>
            <el-input v-else type="number" v-model="scope.row.taxPrice" :min='0' placeholder="请输入(必填)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="总金额(元)" align="center" width="100">
          <template slot-scope="scope">
            <div v-if="flag==1">{{scope.row.totalPrice}}</div>
            <el-input v-else type="number" v-model="scope.row.totalPrice" :min='0' placeholder="请输入(必填)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="操作" align="center" width="50" v-if="flag==0">
          <template slot-scope="scope">
           <el-button type="text" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="dialogOk" v-if="flag!=1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {getCommonCode, listGood, listUnit} from "../../../api/imsMng";
import {deptTreeSelect, listUser} from "../../../api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import {addBuyList} from "../../../api/buyMng";

export default {
  components: {Treeselect},
  dicts:['product_type'],
  data() {
    return {
      flag: 0,
      titles: ['新增', '详情'],
      loading: false,
      dialogVisible: false,
      form: {},
      list:[],
      unitList:[],
      deptList:[],
      userList:[],
      goodList:[]
    }
  },
  watch: {
    'form.deptId'(e) {
      if (e) {
        this.listUSer()
      } else {
        this.$set(this.form, 'userIdList', [])
        this.userList = []
      }
    }
  },
  methods: {
    show(flag, form) {
      this.flag = flag
      this.dialogVisible = true
      this.form = {}
      this.skuForm = {}
      this.resetForm('form')
      if(flag==1){
        this.form=form
        this.list=this.form.itemList
      }
      this.load()
    },
    load(){
      if(!this.flag){
        getCommonCode({orderType: 160}).then(res => {
          this.$set(this.form, 'orderNo', res.data.orderNo)
        })
      }
      listUnit({merchantType:2,pageSize:-1}).then(res=>{
        this.unitList=res.rows
      })
      deptTreeSelect().then(res => {
        this.deptList = res.data
      })
    },
    listUSer() {
      listUser({pageNum: 1, pageSize: 1000, deptId: this.form.deptId}).then(res => {
        this.userList = res.rows
      })
    },
    deleteRow(row){
      this.list=this.list.filter(e=>e!=row)
    },
    changeType(row){
      this.$set(row,'goodList',null)
      this.$set(row,'productId',null)
      this.$set(row,'imageUrl',null)
      listGood({productType:row.productType}).then(res=>{
        this.$set(row,'goodList',res.rows)
      })
    },
    changeGood(row){
      let list=row.goodList.filter(e=>e.id==row.productId)
      if(list&&list.length){
        this.$set(row,'imageUrl',list[0].imageUrl)
        this.$set(row,'productName',list[0].productName)
        this.$set(row,'unit',list[0].unit)
      }
    },
    dialogOk() {
      this.$refs.form.validate(e => {
        if (e) {
          if(!this.list.length){
            this.$message.error('采购项目不能为空')
            return
          }
          let list=this.list.filter(val=>!val.productType||!val.productId||!val.unitPrice
            ||!val.taxRate||!val.taxPrice||!val.totalPrice)
          if(list&&list.length){
            this.$message.error('采购项目必填信息不能为空')
            return
          }
          this.form.itemList=this.list
          this.loading=true
          addBuyList(this.form).then(res=>{
            this.$emit('ok')
            this.dialogVisible=false
            this.$message.success('新增成功')
          }).finally(e => {
            this.loading = false
          })
        }
      })
    },
  }
}
</script>
